(ns scripts.cljmon.csv
  (:use util.file)
  (:require clojure.string))

(defn format-records [data]
  (let [fields (map :value (:data data))]
    (clojure.string/join ", " fields)))

(defn format-headers [fields]
  (clojure.string/join ", " fields))

(defn format-comments [comments]
  (clojure.string/join line-separator
    (for [line (clojure.string/split-lines comments)]
      (if (clojure.string/blank? line)
        "#"
        (str "# " line)))))


(defn parse-comments [lines]
  (remove #(.isEmpty %)
    (map #(clojure.string/replace-first % #"#\s*" "")
      (take-while #(.startsWith % "#")
        lines))))

(defn- name-seq [headers records]
  (map #(zipmap headers %) records))

(defn parse-records [lines]
  (let [[heading & records] (drop-while #(.startsWith % "#") lines)
        headers (clojure.string/split heading #",\s*")
        records (map #(clojure.string/split % #",\s*") records)
        named-records (name-seq headers records)
        columns (map list headers (range))]
    {:headers headers
     :records records
     :named-records named-records
     :columns columns}))
